from sqlalchemy import create_engine, Column, Integer, String, JSON, DateTime, ForeignKey, Float, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from datetime import datetime

metadata = MetaData()
Base = declarative_base(metadata=metadata)

class Calculator(Base):
    __tablename__ = 'calculators'

    id = Column(Integer, primary_key=True, autoincrement=True)  # 自增主键
    name = Column(String, nullable=False)
    version = Column(String, default="0.0")  # 修改为字符串类型
    code = Column(String)
    status = Column(String, default='draft')
    inputs = Column(JSON)
    access_control = Column(JSON)
    created_at = Column(DateTime, default=datetime.now)
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)

class Task(Base):
    __tablename__ = 'tasks'

    id = Column(Integer, primary_key=True, autoincrement=True)
    calculator_id = Column(String, ForeignKey('calculators.id'))
    username = Column(String, nullable=False)
    inputs = Column(JSON)
    output = Column(JSON)
    timestamp = Column(DateTime, default=datetime.now)
    calculator_version = Column(Integer)

class DraftInput(Base):
    __tablename__ = 'draft_inputs'

    id = Column(String, primary_key=True)
    calculator_id = Column(String, ForeignKey('calculators.id'))
    username = Column(String, nullable=False)
    data = Column(JSON)
    timestamp = Column(DateTime, default=datetime.now)

class UserAuditLog(Base):
    __tablename__ = 'user_audit_logs'

    id = Column(Integer, primary_key=True)
    timestamp = Column(DateTime, default=datetime.now)
    username = Column(String, nullable=False)
    target_user_id = Column(String)  # 新增字段：被操作的用户ID
    action = Column(String, nullable=False)
    details = Column(String)

class CalculatorAuditLog(Base):
    __tablename__ = 'calculator_audit_logs'

    id = Column(Integer, primary_key=True)
    calculator_id = Column(String, ForeignKey('calculators.id'))
    timestamp = Column(DateTime, default=datetime.now)
    username = Column(String, nullable=False)
    action = Column(String, nullable=False)
    details = Column(String)
    old_value = Column(JSON)
    new_value = Column(JSON)

# 数据库连接
engine = create_engine('sqlite:///calculator.db', echo=False)
Session = sessionmaker(bind=engine)

def init_db():
    """初始化数据库"""
    Base.metadata.create_all(engine)

def get_session():
    """获取数据库会话"""
    return Session()

def get_next_calculator_id():
    """获取下一个计算器ID"""
    session = get_session()
    try:
        max_id = session.query(Calculator.id).order_by(Calculator.id.desc()).first()
        if max_id is None:
            return "C-1"
        current_num = int(max_id[0].split('-')[1])
        return f"C-{current_num + 1}"
    finally:
        session.close()
